var publishWrap = $('#publish');
var stepWrap = publishWrap.find('.step.container');
var stepNavs = publishWrap.find('.step li');
var btnWrap = publishWrap.find('.main-do');
var preStep2 = $('#preStep2');
var preStep3 = $('#preStep3');
var nextStep1 = $('#nextStep1');
var nextStep2 = $('#nextStep2');
var confirmStep = $('#confirmStep');
var continuePublish = $('#continuePublish');
var infoCenter = $('#infoCenter');
var infoTypeRadio1 = $('#type-01');
var infoTypeRadio2 = $('#type-02');

var containers = publishWrap.find('div.container');
var typeContainer = publishWrap.find('.container.type');

// 区域选择
var areaContainer = publishWrap.find('.container.area');
var areaTypeText = publishWrap.find('.select-type'); // 信息类型文字显示
var areaWrap = areaContainer.find('.area-container'); // 行政区列表
var areaShopWrap = areaContainer.find('.subArea .con'); // 行政区商圈列表
var subwayWrap = areaContainer.find('.subway-container'); // 地铁列表
var subwayStationWrap = areaContainer.find('.subStation .con'); // 地铁站点列表

// 详细信息
var moreinfoForm = $('#moreinfoForm');
var areaSelectText = publishWrap.find('.select-area'); // 区域文字显示
var moreContainer = publishWrap.find('.container.more'); // 详细信息
var moreInfoTypeTip = $('.more-info-type'); // 标题类型
var moreInfoTitle = $('#more-info-title'); // 标题
var moreInfoCategory = $('#more-info-category'); // 行业选择
var moreInfoEstateType = $('#more-info-estate-type'); // 商铺类型
var moreInfoAddress = $('#more-info-address'); // 地标性说明
var moreInfoEmptyAttorn = $('#more-info-empty'); // 空转checkbox
var moreInfoIsOperating = $('#more-info-operating'); // 营业中checkbox
var moreInfoAreaSize = $('#more-info-area-size'); // 面积输入框
var moreInfoAreaSize2 = $('#more-info-area-size2'); // 面积输入框最小值
var moreInfoAreaSize3 = $('#more-info-area-size3'); // 面积输入框最大值
var moreInfoRent = $('#more-info-rent'); // 租金输入框
var moreInfoPropertyFee = $('#more-info-property-fee'); // 物业费输入框
var moreInfoBargaining = $('#more-info-bargaining-checkbox'); // 转让费面议checkbox
var moreInfoTransFee = $('#more-info-transfer-fee'); // 转让费输入框
var moreInfoTransFee2 = $('#more-info-transfer-fee2'); // 转让费上限输入框
var moreInfoTransScope = $('#more-info-transfer-scope'); // 转让费价格浮动范围
var moreInfoDesc = $('#more-info-desc'); // 详细介绍输入框
var moreInfoImages = $('#moreinfoImagesWrap'); // 商铺图片列表
var moreInfoImagesAddLi = moreInfoImages.find('.add'); // 商铺图片添加按钮
var moreInfoIdentityPro = $('#identity-proprietor'); // 身份：业主radiobox
var moreInfoIdentityLand = $('#identity-landlord'); // 身份：房东radiobox
var moreInfoIdentityInter = $('#identity-intermediary'); // 身份：中介radiobox
var moreInfoContactDefault = $('#more-info-default-contact'); // 默认联系方式 ?
var moreInfoContactName = $('#more-info-contact-name'); // 联系姓名
var moreInfoContactPhone = $('#more-info-contact-phone'); // 联系电话

// 发布结束
var finishContainer = publishWrap.find('.container.finish');
var storePublishStr = sessionStorage.getItem('publish-info');
var finishTitle = $('#finish-title-tip');
console.log(SITE_ID);
var storePublishInfo = {
    step: 1
};

var cityDatas = {
    city: CITY_ID,
    areas: {},
    subways: {}
};

if (storePublishStr) {
    var storePublishInfo = JSON.parse(storePublishStr);
}

// 根据存储的发布信息更新页面
function initInfo() {
    var curStep = storePublishInfo.step;

    containers.hide();
    stepWrap.show();
    stepNavs.removeClass('active');
    switch(curStep) {
        case 1:
            typeContainer.show();
            $(stepNavs.get(0)).addClass('active');
            break;
        case 2:
            areaContainer.show();
            $(stepNavs.get(1)).addClass('active');
            break;
        case 3:
            moreContainer.show();
            $(stepNavs.get(2)).addClass('active');
            break;
        case 4:
            stepWrap.hide();
            finishContainer.show();
            break;
    }

    if (4 == curStep) {
        return;
    }

    // 信息类型设置
    if (storePublishInfo.info_type) {
        if (1 == storePublishInfo.info_type * 1) {
            infoTypeRadio1[0].checked = true;
            areaTypeText.text('商铺转让');
            moreInfoTypeTip.text('转让');

            moreContainer.removeClass('show-seeklease');
        }
        else if (2 == storePublishInfo.info_type * 1) {
            infoTypeRadio2[0].checked = true;
            areaTypeText.text('商铺求租');
            moreInfoTypeTip.text('求租');

            moreContainer.addClass('show-seeklease');
        }
    }

    // 商铺区域顶部文字拼接
    var areaSelectTextStr = [];
    if (storePublishInfo.area) {
        areaSelectTextStr.push([storePublishInfo.area, storePublishInfo.areaShop].join(' '));
        buildAreaDataHTML(storePublishInfo.area, storePublishInfo.areaIndex, storePublishInfo.areaShop);
    }
    if (storePublishInfo.subway) {
        areaSelectTextStr.push([storePublishInfo.subway, storePublishInfo.subwayStation].join(' '));
        buildSubwayDataHTML(storePublishInfo.subway, storePublishInfo.subwayIndex, storePublishInfo.subwayStation);
    }
    if (areaSelectTextStr.length > 0) {
        areaSelectText.text(areaSelectTextStr.join(' , '));
    }
}

// 检查填写的值
function checkValue() {
    var curStep = storePublishInfo.step;

    switch(curStep) {
        case 1:
            if (!infoTypeRadio1[0].checked && !infoTypeRadio2[0].checked) {
                bootbox.alert('未选择信息类型');
                return false;
            }
            break;
        case 2:
            if (!storePublishInfo.area && !storePublishInfo.subway) {
                bootbox.alert('请选择商铺所在区域');
                return false;
            }
            break;
        case 3:
            break;
        case 4:
            break;
    }

    return true;
}

// 获取当前城市商圈数据
function getBusinessData(callback) {
    // var sessionCity = sessionStorage.getItem('city-infos');
    var sessionCity = '';
    if (sessionCity) {
        cityDatas = JSON.parse(sessionCity);

        console.log(cityDatas);

        buildBusinessData();

        callback && callback();
    }
    else {
        $.ajax({
            type: "GET",
            url: SITE_ADDR + "/city/" + cityDatas.city,
            success: function (data, textStatus) {
                console.log(data);

                cityDatas.areas = data.areas;
                cityDatas.subways = data.subways;

                sessionStorage.setItem('city-infos', JSON.stringify(data));

                buildBusinessData();

                callback && callback();
            }
        });
    }
}

// 根据行政区数据创建html
function buildAreaDataHTML(area, areaIndex, areaShop) {
    var areaHtmlStr = [];

    cityDatas.areas.forEach(function (item, idx) {
        if (area && area == item.name) {
            areaHtmlStr.push('<label class="radio-inline"><input type="radio" name="areaRadio" checked="checked" value="' + idx + '">' + item.name + '</label>');
        }
        else {
            areaHtmlStr.push('<label class="radio-inline"><input type="radio" name="areaRadio" value="' + idx + '">' + item.name + '</label>');
        }
    });

    areaWrap.html(areaHtmlStr.join(''));
    areaShopWrap.html('').hide();

    if (area && cityDatas.areas[areaIndex]) {
        buildShopDataHTML(areaIndex, areaShop);
    }
}

// 根据商圈数据创建html
function buildShopDataHTML(areaIndex, areaShop) {
    if ('全城' == cityDatas.areas[areaIndex].name) {
        areaShopWrap.html('').hide();
        return;
    }

    var shopAreas = cityDatas.areas[areaIndex].shopAreas;

    var shopStr = ['<h5>商圈:</h5>'];

    shopAreas.forEach(function(item, index) {
        if (areaShop && areaShop == item.name) {
            shopStr.push('<label class="radio-inline"><input type="radio" name="areaShopRadio" checked="checked" value="' + item.name + '">' + item.name + '</label>');
        }
        else {
            shopStr.push('<label class="radio-inline"><input type="radio" name="areaShopRadio" value="' + item.name + '">' + item.name + '</label>');
        }
    });

    areaShopWrap.html(shopStr.join('')).show();
}

// 根据地铁数据创建html
function buildSubwayDataHTML(subway, subwayIndex, subwayStation) {
    var subwayHtmlStr = [];

    cityDatas.subways.forEach(function (item, idx) {
        if (subway && subway == item.name) {
            subwayHtmlStr.push('<label class="radio-inline"><input type="radio" name="subwayRadio" checked="checked" value="' + idx + '">' + item.name + '</label>');
        }
        else {
            subwayHtmlStr.push('<label class="radio-inline"><input type="radio" name="subwayRadio" value="' + idx + '">' + item.name + '</label>');
        }
    });

    subwayWrap.html(subwayHtmlStr.join(''));
    subwayStationWrap.html('').hide();

    if (subway && cityDatas.subways[subwayIndex]) {
        buildStationDataHTML(subwayIndex, subwayStation);
    }
}

// 更具地铁线路创建站点html
function buildStationDataHTML(subwayIndex, station) {
    var subwayStations = cityDatas.subways[subwayIndex].stations;

    var stationsStr = ['<h5>站点:</h5>'];

    subwayStations.forEach( function(item, index) {
        if (station && station == item) {
            stationsStr.push('<label class="radio-inline"><input type="radio" name="subwayStationRadio" checked="checked" value="' + item + '">' + item + '</label>');
        }
        else {
            stationsStr.push('<label class="radio-inline"><input type="radio" name="subwayStationRadio" value="' + item + '">' + item + '</label>');
        }
    });

    subwayStationWrap.html(stationsStr.join('')).show();
}

// 创建区域选择框
function buildBusinessData() {
    // 行政区
    if (cityDatas && cityDatas.areas && cityDatas.areas.length > 0) {
        buildAreaDataHTML();

        areaWrap.on('change', 'input[name=areaRadio]', function () {
            var areaIndex = $('input[name=areaRadio]:checked').val();
            console.log('checked radio: ', areaIndex);

            storePublishInfo.area = cityDatas.areas[areaIndex].name;
            storePublishInfo.areaIndex = areaIndex;
            storePublishInfo.areaShop = '';

            buildShopDataHTML(areaIndex);
        });

        areaShopWrap.on('change', 'input[name=areaShopRadio]', function () {
            var areaShopName = $('input[name=areaShopRadio]:checked').val();

            storePublishInfo.areaShop = areaShopName;
        });
    }
    else {
        bootbox.alert('商圈数据获取失败，请稍后再尝试');
    }

    // 地铁线
    if (cityDatas && cityDatas.subways && cityDatas.subways.length > 0) {
        buildSubwayDataHTML();

        subwayWrap.on('change', 'input[name=subwayRadio]', function () {
            var subwayIndex = $('input[name=subwayRadio]:checked').val();
            console.log('checked radio: ', subwayIndex);

            storePublishInfo.subway = cityDatas.subways[subwayIndex].name;
            storePublishInfo.subwayIndex = subwayIndex;
            storePublishInfo.subwayStation = '';

            buildStationDataHTML(subwayIndex);
        });

        subwayStationWrap.on('change', 'input[name=subwayStationRadio]', function () {
            var stationName = $('input[name=subwayStationRadio]:checked').val();

            storePublishInfo.subwayStation = stationName;
        });
    }
}

var genderLabel = $('#more-info-select-gender-label');
// 更多信息里选择性别
function moreInfoSelectGender(gender) {
    console.log('gender: ', gender);
    if ('female' == gender) {
        genderLabel.text('女士');
        storePublishInfo.gender = 'female';
    }
    else {
        genderLabel.text('先生');
        storePublishInfo.gender = 'male';
    }
}
window.moreInfoSelectGender = moreInfoSelectGender;


// 根据填写的详细信息拼接信息发布参数
function buildInfoSubmitData() {
    var submitJson = {
        infoSource: 'PERSONAL',  // 页面上提交的应该都是会员
        estateType : "Store", // 暂时都是商铺
        user: userName,
        isDeleted : false,
        isPreference : false,
        isTraded : true, // ?
        estate: {
            city: CITY
        }, // 商铺详情
        contact: {}, // 联系方式

        // 以下待定
        level: 0,
        site: SITE_ID,
        tags: []
    };

    var isAttorn = (1 == storePublishInfo.info_type * 1);

    if (
        '选择行业' == moreInfoCategory.val()
        || '选择类型' == moreInfoEstateType.val()
        || !moreInfoRent.val() || !moreInfoPropertyFee.val()
        || (isAttorn && (!moreInfoAreaSize.val() || !moreInfoTransFee.val()))
        || (!isAttorn && (!moreInfoAreaSize2.val() || !moreInfoAreaSize3.val() || !moreInfoTransFee2.val()))
        ) {
        bootbox.alert('还有信息未选择或填写');
        return false;
    }

    submitJson['category'] = moreInfoCategory.val();
    submitJson['title'] = moreInfoTitle.val();
    submitJson['content'] = moreInfoDesc.val();
    submitJson.contact['name'] = moreInfoContactName.val();
    submitJson.contact['phone'] = moreInfoContactPhone.val();

    // 身份区分
    if (moreInfoIdentityPro.is(':checked')) {
        submitJson.contact['identity'] = 'proprietor'; // 业主
    }
    if (moreInfoIdentityLand.is(':checked')) {
        submitJson.contact['identity'] = 'landlord'; // 业主
    }
    if (moreInfoIdentityInter.is(':checked')) {
        submitJson.contact['identity'] = 'intermediary'; // 业主
    }
    // 性别
    submitJson.contact['gender'] = ('female' == storePublishInfo.gender) ? 'femal' : 'male';


    submitJson.estate['canEmptyAttorn'] = moreInfoEmptyAttorn.is(':checked');
    submitJson.estate['isOperating'] = moreInfoIsOperating.is(':checked');
    submitJson.estate['canBargaining'] = moreInfoBargaining.is(':checked');
    submitJson.estate['location'] = moreInfoAddress.val();

    if (isAttorn) {
        submitJson['infoType'] = 'Attorn';
        submitJson['images'] = storePublishInfo.images;
        submitJson.estate['type'] = moreInfoEstateType.val();
        submitJson.estate['transferFee'] = parseInt(moreInfoTransFee.val());
        submitJson.estate['offset'] = parseInt(moreInfoTransScope.val());
        submitJson.estate['area'] = parseInt(moreInfoAreaSize.val());
        submitJson.estate['rental'] = parseInt(moreInfoRent.val());
        submitJson.estate['propertyFee'] = parseInt(moreInfoPropertyFee.val());
        submitJson.estate['district'] = storePublishInfo.area;
        submitJson.estate['shopArea'] = storePublishInfo.areaShop;
        submitJson.estate['subway'] = storePublishInfo.subway;
        submitJson.estate['station'] = storePublishInfo.subwayStation;
    }
    else {
        submitJson['infoType'] = 'SeekLease';
        // 求租的商铺类型值是数组
        submitJson.estate['type'] = [moreInfoEstateType.val()];
        submitJson.estate['transferFee'] = {min: 0, max: parseInt(moreInfoTransFee2.val())};
        submitJson.estate['area'] = {min: parseInt(moreInfoAreaSize2.val()), max: parseInt(moreInfoAreaSize3.val())};
        submitJson.estate['rental'] = {min:0, max: parseInt(moreInfoRent.val())};
        submitJson.estate['propertyFee'] = {min:0, max: parseInt(moreInfoPropertyFee.val())};
        submitJson.estate['district'] = [storePublishInfo.area];
        submitJson.estate['shopArea'] = [storePublishInfo.areaShop];
        submitJson.estate['subway'] = [storePublishInfo.subway];
        submitJson.estate['station'] = [storePublishInfo.subwayStation];
    }

    return submitJson;
}

$(document).ready(function(){
    // --------------------------各个步骤按钮事件处理--------------------------
    nextStep1.click(function () {
        if (!checkValue()) {
            return;
        }

        storePublishInfo.info_type = infoTypeRadio1[0].checked ? 1 : 2;
        storePublishInfo.step = 2;

        sessionStorage.setItem('publish-info', JSON.stringify(storePublishInfo));

        initInfo();
    });
    preStep2.click(function () {
        storePublishInfo.step = 1;

        sessionStorage.setItem('publish-info', JSON.stringify(storePublishInfo));

        initInfo();
    });
    nextStep2.click(function () {
        if (!checkValue()) {
            return;
        }
        storePublishInfo.step = 3;

        sessionStorage.setItem('publish-info', JSON.stringify(storePublishInfo));

        initInfo();
    });
    preStep3.click(function () {
        storePublishInfo.step = 2;

        sessionStorage.setItem('publish-info', JSON.stringify(storePublishInfo));

        initInfo();
    });
    confirmStep.click(function () {
        // moreinfoForm.trigger("validate");
        moreinfoForm.submit();
    });
    continuePublish.click(function () {
        storePublishInfo = {step: 1};

        location.href = '/'+CITY+'/publish';
    });
    infoCenter.click(function () {
        location.href = '/'+CITY+'/perCenter';
    });


    // --------------------------信息提交--------------------------
    var submiting = false;
    moreinfoForm.validator().on('submit', function (e) {
        if (e.isDefaultPrevented()) {
            bootbox.alert('还有信息未填写');
            return false;
        }

        // 转让的信息需要提供图片
        if (1 == storePublishInfo.info_type * 1) {
            if (!storePublishInfo.images || storePublishInfo.images.length < 1 || storePublishInfo.images.length > 6) {
                bootbox.alert('至少上传 1 张图片，最多上传 6 张图片');
                return false;
            }
        }

        var postdata = buildInfoSubmitData();

        if (!postdata) {
            return false;
        }

        if (submiting) {
            return false;
        }
        submiting = true;

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: SITE_ADDR + "/info",
            data: JSON.stringify(postdata),
            success: function (data, textStatus) {
                if (data.result.ok) {
                    console.log('发布成功');
                    storePublishInfo.step = 4;
                    sessionStorage.removeItem('publish-info');

                    var titleHtml = ['<a href="/'+CITY+'/detail/' + data.insertedIds + '"><strong class="more-info-type">',
                                        ((1 == storePublishInfo.info_type * 1) ? '转让' : '求租'),
                                        '</strong>',
                                        moreInfoTitle.val(),
                                    '</a><small>No.' + data.insertedIds + '</small>'].join('');
                    finishTitle.html(titleHtml);
                    initInfo();
                }
                else {
                    bootbox.alert('没发布成功');
                }
            },
            complete: function (XMLHttpRequest, textStatus) {
                submiting = false;
            }
        });
        return false;
    });

    // --------------------------区域选取--------------------------
    getBusinessData(function () {
        initInfo();
    });

    // --------------------------图片上传--------------------------
    // 限制图片宽高为: 600 * 450
    function enforceWidthHeight(file) {
        return new Promise(function (resolve) {
            var reader = new FileReader();

            reader.onload = function (evt) {
                var image = new Image();

                image.onload = function () {
                    var error = (this.width != 600 || this.height !=450) ?
                        "宽高错误，需要为 600px * 450px" : null;
                    resolve(error);
                };

                image.src = evt.target.result;
            };

            reader.readAsDataURL(file);
        });
    }
    // 渲染上传成功的图片至页面上
    function renderUploadImages(imgSrc) {
        var imgLiHtmlStr = '<li data="' + imgSrc + '" style="background-image:url(' + imgSrc + ');"><a href="javascript:;"><i class="fa fa-trash-o"></i></a></li>';

        $(imgLiHtmlStr).insertBefore(moreInfoImagesAddLi);
    }
    // 图片上传
    $(".fileUpload").liteUploader({
        script: SITE_ADDR + "/upload"
        ,singleFileUploads: true
        // , validators: [enforceWidthHeight] // 宽高限制
    })
    .on("lu:errors", function (e, errors) {
        console.log(errors);
        if (errors && errors.length > 0) {
            var errStr = '上传图片[' + errors[0].name + ']错误：' + errors[0].errors.join(',');
            bootbox.alert(errStr);
        }
    })
    .on("lu:success", function (e, response) {
        console.log(response);
        var response = JSON.parse(response);
        if (response && response.ops && response.ops.length > 0 && response.ops[0].path) {
            if (!storePublishInfo.images) {
                storePublishInfo.images = [];
            }
            storePublishInfo.images.push(response.ops[0].path);

            renderUploadImages(response.ops[0].path);

            if (storePublishInfo.images.length > 6) {
                bootbox.alert('最多上传 6 张图片，请删掉一些图片。');
            }
        }
        else {
            bootbox.alert('图片上传失败，请稍后再试或联系管理员。');
        }
    });

    $(".fileUpload").change(function () {
        $(this).data("liteUploader").startUpload();
    });

    // 删除上传图片
    moreInfoImages.on('click', 'li a', function (e) {
        var theLi = $(this).parent();
        var theSrc = theLi.attr('data');
        console.log(theSrc);

        theLi.remove();
        if (storePublishInfo.images && storePublishInfo.images.indexOf(theSrc) > -1) {
            storePublishInfo.images.splice(storePublishInfo.images.indexOf(theSrc), 1);
        }

        console.log('newStorePublishInfo: ');
        console.log(storePublishInfo);
    });

});
